"""删除中心"""
from src.core import Enums
from src.db import dbm, dbs
from src.core.variables.status import *
from src.core.variables.status import *
from src.core.variables.exception import *
from src.apps.hosting.stater.controller import Jar_manager
from src.core.variables.cls import HOSTING_JAVA_RUNNER_DICT, HOSTING_STATIC_RUNNER_DICT
from src.schema.hosting import remove_static_record_schema, remove_app_schema


def java(schema: remove_app_schema):
    runner = HOSTING_JAVA_RUNNER_DICT.get(schema.app_id, None)
    if runner is not None:
        if runner.status == Enums.AppStatus.JAVA_STATUS.RUNNING:
            runner.stop()
    else:
        runner = Jar_manager(schema.back_id)
    runner.remove()
    with dbm.get("hosting_Java") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_session.query(dbs.hosting_Java.App).filter(
            dbs.hosting_Java.App.app_id == schema.app_id
        ).delete()
        db_session.query(dbs.hosting_Java.App_backup).filter(
            dbs.hosting_Java.App_backup.app_id == schema.app_id
        ).delete()
        if not dbm.commit(db_session):
            db_session.rollback()
            raise MAIN_EXCEPTION(f"提交数据库更改失败！")
        return SUCCESS_CODE.APP_REMOVE(f"应用删除成功！")


def static(schema: remove_static_record_schema):
    runner = HOSTING_STATIC_RUNNER_DICT.get(schema.app_id, None)
    if runner is not None:
        runner.remove()
    with dbm.get("hosting_Static") as db_session:
        db_session.query(dbs.hosting_Static.App).filter(
            dbs.hosting_Static.App.app_id == schema.app_id
        ).delete()
        db_session.query(dbs.hosting_Static.App_backup).filter(
            dbs.hosting_Static.App_backup.app_id == schema.app_id
        ).delete()
        if not dbm.commit(db_session):
            db_session.rollback()
            raise MAIN_EXCEPTION(f"提交数据库更改失败！")
        return SUCCESS_CODE.APP_REMOVE(f"应用删除成功！")